package com.maicss.coursedesign.servlet;

import com.maicss.coursedesign.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
// 负责登录和注册相关工作
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String type = req.getParameter("type");
        if (type==null){
            // 如果没有提供type参数，则重定向到login.jsp中
            resp.sendRedirect("login.jsp");
        }else if (type.equals("login")){
            serviceLogin(req,resp);
        }else if (type.equals("register")){
            serviceRegister(req,resp);
        }
    }
    
    protected void serviceLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user_name = req.getParameter("user_name");
        String user_pwd = req.getParameter("user_pwd");
        // 从数据库中查询该用户是否存在并验证密码是否正确
        if (UserDao.UserCheck(user_name,user_pwd)){
            req.getSession().setAttribute("user",user_name);
            resp.sendRedirect("index.jsp");
        }else {
            req.setAttribute("title","登录失败");
            req.setAttribute("context","您的用户名或密码无效，请重新登录。若您没有帐号，可以点击<a href=\"login/loginPage.jsp#register\">注册申请帐号</a>。");
            req.getRequestDispatcher("login/message.jsp").forward(req,resp);
        }
    }

    protected void serviceRegister(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user_name = req.getParameter("user_name");
        String user_pwd = req.getParameter("user_pwd");
        String invitationCode = req.getParameter("user_invitation_code");

        if(UserDao.UserRegister(user_name,user_pwd,invitationCode)){
            req.setAttribute("title","注册成功");
            req.setAttribute("context","恭喜您 "+user_name+"，您已经注册成功，现在可以使用此账户<a href=\"login/loginPage.jsp#login\">登录</a>。");
            req.getRequestDispatcher("login/message.jsp").forward(req,resp);
        }else {
            req.setAttribute("title","注册失败");
            req.setAttribute("context","很抱歉，您的账户没有成功注册，请检查用户名是否已经存在或邀请码是否有效。您可以<a href=\"login/loginPage.jsp#register\">重新注册</a>。");
            req.getRequestDispatcher("login/message.jsp").forward(req,resp);
        }

    }
}
